/**
 * elancom Corporation copy right 2012 - 2015  
 *   
 * $Header$
 * $Id$
 * $Author$
 * $Date$
 * $Revision$
 */
package com.elancom.framework.component.interceptor;

import com.elancom.framework.component.Component;
import com.elancom.framework.component.ComponentException;
import com.elancom.framework.component.Input;
import com.elancom.framework.component.Invocation;
import com.elancom.framework.component.InvocationContext;
import com.elancom.framework.component.Output;
import com.elancom.framework.component.validate.ValidateSupport;
import com.elancom.framework.component.validate.Validator;

/**
 * @author elancom
 * @date 2012-8-22
 */
public class ValidateInterceptor implements Interceptor {

	/*
	 * (non-Javadoc)
	 * @see com.elancom.framework.component.interceptor.Interceptor#intercept(com.elancom.framework.component.Invocation)
	 */
	@Override
	public Object intercept(Invocation invocation) throws ComponentException {
		Object rs = null;

		InvocationContext context = invocation.getContext();
		Component component = context.getComponent();
		Output output = context.getOutput();
		Input input = context.getInput();

		if (component instanceof Validator) {
			((Validator) component).validate(input, output);
			if (output.hasError()) {
				return rs; // fail
			}
		}

		if (component instanceof ValidateSupport) {
			Validator validator = ((ValidateSupport) component).getValidator();
			if (validator != null) {
				validator.validate(input, output);
			}
			if (output.hasError()) {
				return rs; // fail
			}
		}

		rs = invocation.invoke();
		return rs;
	}
}
